<template>
    <div class="menu-config">
        <div class="page-header">
            <h2>菜单管理</h2>
            <div>
                <el-button type="primary" @click="openAddDialog">添加菜单</el-button>
                <el-button :icon="Refresh" @click="refreshMenus" circle />
            </div>
        </div>

        <!-- 菜单列表 -->

        <el-table max-height="calc(100vh - 210px)" :default-expand-all="false" :data="menus" border style="width: 100%"
            row-key="id">
            <el-table-column prop="title" label="权限菜单名称" width="200" />
            <el-table-column prop="path" label="路由地址" />
            <el-table-column prop="name" label="路由别名" />
            <el-table-column prop="component" label="组件路径" />
            <el-table-column label="类型">
                <template #default="{ row }">
                    <el-tag :type="row.type === 2 ? 'success' : row.type === 1 ? 'info' : 'warning'">
                        {{ row.type === 2 ? '菜单' : row.type === 1 ? '页面' : '按钮' }}
                    </el-tag>
                </template>

            </el-table-column>

            <el-table-column prop="enable" label="状态" width="100">
                <template #default="{ row }">
                    <el-tag :type="row.enable ? 'success' : 'error'">
                        {{ row.enable ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="loading" label="加载框" width="100">
                <template #default="{ row }">
                    <el-tag :type="row.loading ? 'success' : 'error'">
                        {{ row.loading ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="icon" label="图标" width="100">

            </el-table-column>

            <el-table-column prop="description" label="描述" />

            <el-table-column label="操作" width="200">
                <template #default="{ row }">
                    <el-button type="text" :icon="Edit" @click="openEditDialog(row)" />
                    <el-button type="text" danger :icon="Delete" @click="deleteMenu(row.id)" />
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加/编辑菜单弹窗 -->
        <el-dialog v-model="dialogVisible" title="菜单配置" width="400px" :before-close="closeDialog">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="菜单名称" prop="title">
                    <el-input v-model="form.title" placeholder="请输入菜单名称" />
                </el-form-item>
                <el-form-item label="路由地址" prop="path">
                    <el-input v-model="form.path" placeholder="请输入路由地址" />
                </el-form-item>
                <el-form-item label="组件路径" prop="component">
                    <el-input :disabled="form.type === 2" v-model="form.component" placeholder="请输入路由地址" />
                </el-form-item>
                <el-form-item label="路由别名" prop="name">
                    <el-input :disabled="form.type === 2" v-model="form.name" placeholder="请输入路由地址" />
                </el-form-item>
                <!-- 上级关系 -->
                <el-form-item label="上级菜单" prop="superiorRelation">
                    <el-cascader v-model="form.superiorRelation" placeholder="请选择上级部门关系" :options="options"
                        :props="{ checkStrictly: true }" @change="handleChange" />
                    <el-button class="refreshSuperiorRelation" :icon="Refresh" @click="refreshOptions" size="small"
                        circle />
                </el-form-item>
                <el-form-item label="菜单描述" prop="description">
                    <el-input v-model="form.description" placeholder="请输入菜单描述" />
                </el-form-item>
                <el-form-item label="配置类型">
                    <el-radio-group v-model="form.type">
                        <el-radio-button label="按钮" :value="0" />
                        <el-radio-button label="页面" :value="1" />
                        <el-radio-button label="菜单" :value="2" />
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="启用状态">
                    <el-switch v-model="form.enable" active-text="启用" inactive-text="禁用" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="saveMenu">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, inject } from 'vue';
import { ElMessage } from 'element-plus';
import { Refresh, Delete, Edit } from '@element-plus/icons-vue';
import { openLoading, closeLoading } from '../../utils/loading';

const axios = inject('$axios'); // 从全局属性注入 axios

// 菜单数据（包含按钮权限假数据）
const menus = ref([]);

const dialogVisible = ref(false); // 菜单配置弹窗显示状态
const formRef = ref(null); // 表单引用
// 菜单表单数据
const form = reactive({
    id: 0,
    name: '',
    description: '',
    path: '',
    type: 2,
    superiorRelation: '',
    enable: true,
    component: '',
    title: '',
    type: 2
});
const options = ref([])

// 表单校验规则
const rules = {
    title: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
    // path: [{ required: true, message: '请输入路由地址', trigger: 'blur' }],
    // component: [{ required: true, message: '请输入组件路径', trigger: 'blur' }],
};

// 打开添加菜单弹窗
const openAddDialog = () => {
    dialogVisible.value = true;
};

//获取关系
let superiorRelation = '';
const handleChange = (value) => {
    const newValue = value.map(item => item.toString().toLowerCase()).join(','); // 将选中的值转为小写字符串
    superiorRelation = newValue
}

// 打开编辑菜单弹窗
const openEditDialog = (row) => {
    if (typeof row.superiorRelation === 'string') {
        superiorRelation = row.superiorRelation;
        // 保存原始字符串
        const originalRelation = row.superiorRelation;
        // 将字符串转换为数组
        row.superiorRelation = originalRelation.split(',');
    } else {
        // 如果不是字符串，则处理数据并回退到原值
        handleChange(row.superiorRelation);
        row.superiorRelation = Array.isArray(row.superiorRelation)
            ? row.superiorRelation
            : []; // 如果不是数组，设置为空数组
    }

    row.path = row.path.replace(/^\//, '');
    console.log(row.superiorRelation);
    Object.assign(form, row);
    dialogVisible.value = true;
};
// 关闭菜单配置弹窗
const closeDialog = () => {
    Object.assign(form, { id: 0, name: '', title: '', description: '', component: '', path: '', enable: true, type: 2, superiorRelation: '' });
    dialogVisible.value = false;
};
// 保存菜单
const saveMenu = async () => {
    //校验
    const valid = await new Promise((resolve, reject) => {
        formRef.value.validate((valid) => {
            if (!valid) {
                ElMessage.error('请完善必填项');
                return (new Error('请完善必填项'));
            } else {
                resolve(valid)
            }
        })
    })

    //传参数据
    var dataParam = {
        'Id': form.id ?? 0,
        'Name': form.name,
        'description': form.description,
        'path': form.path ?? 0,
        'Enable': form.enable,
        'SuperiorRelation': superiorRelation || "0",
        'type': form.type,
        'Title': form.title,
        'Component': form.component
    }

    let result;
    if (dataParam.Id > 0) {
        // 编辑部门，执行更新操作
        result = await axios.post('/Permission/EditMenuAsync', dataParam);
    } else {
        // 添加部门，执行添加操作
        result = await axios.post('/Permission/AddMenuAsync', dataParam);
    }

    if (result.statusCode == 200 && result.success == true) {
        getMenus();
        setTimeout(() => {
            GetMenusByCascaderAsync();
        }, 500);
        ElMessage.success(result.message);
    } else {
        ElMessage.error(result.message);
    }

    closeDialog();
};
//获取上层部门层级数据
const GetMenusByCascaderAsync = async () => {
    var result = await axios.get('/Permission/QueryMenusByCascaderAsync')
    if (result.statusCode == 200 && result.success == true) {
        options.value = result.response
    }
}
//刷新上层部门层级数据
const refreshOptions = () => {
    GetMenusByCascaderAsync();
}
// 删除菜单
const deleteMenu = async (id) => {
    const result = await axios.get('/Permission/DeleteMenusAsync?id=' + id);
    if (result.statusCode == 200 && result.success == true) {
        ElMessage.success('删除成功');
        getMenus();
    } else {
        ElMessage.error(result.message);
    }
};
// 获取数据
const getMenus = async () => {
    const result = await axios.get('/Permission/QueryMenusAsync');
    if (result.statusCode == 200 && result.success == true) {
        menus.value = result.response;
    } else {
        ElMessage.error('获取用户列表失败');
    }
};

// 刷新菜单
const refreshMenus = async () => {
    await getMenus();
    ElMessage.success('菜单已刷新');
};

onMounted(() => {
    getMenus();
    // 延迟 0.5 秒发送请求
    setTimeout(async () => {
        try {
            GetMenusByCascaderAsync();
        } catch (error) {
            console.error("请求失败", error);
        }
    }, 500); // 延迟500毫秒
    closeLoading()
})
</script>

<style scoped>
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.el-button {
    margin-left: 10px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    padding: 10px;
}
</style>
